package com.example.demo.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.example.demo.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/api")
@CrossOrigin(origins = "*", maxAge = 3600)
@Slf4j
public class ApiController {


    @PostMapping("/upload")
    @ResponseBody
    public R<String> upload(HttpServletRequest request, @RequestParam("image") MultipartFile image) {
        log.info("image{}", image.toString());
        // 将上传的文件保存到本地临时目录中，用于构建HTTP multipart/form-data请求
        File file = null;
        try {
            file = FileUtil.writeBytes(
                    image.getBytes(),
                    FileUtil.getTmpDirPath() +
                            File.separator +
                            image.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            log.info("file提取失败");
            return R.error("file提取失败");
        }

        // 构建HTTP multipart/form-data请求
        String url = "https://img.atanycosts.cn/api/index.php";
        HttpResponse response = null;
        response = HttpRequest.post(url)
                .header("Content-Type", "multipart/form-data")
                .header("Access-Control-Allow-Origin", "*")
                .form("image", file)
                .form("token", "bcf162b45801c9b5fbfaa844565e44aa") // token写死
                .execute();

        // 从响应中获取处理结果
        JSONObject resultJson = new JSONObject(response.body());
        int code = resultJson.getInt("code");
        if (code == 200) {
            return R.success(resultJson.getStr("url"));
        } else {
            String msg = resultJson.getStr("result");
            return R.error(msg);
        }
    }
}
